package com.gosling.gosling.ziruan;

import com.ximpleware.*;
import com.ximpleware.extended.*;
import com.ximpleware.extended.FastLongBuffer;
import com.ximpleware.extended.IByteBuffer;
import org.apache.poi.util.IOUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.DigestUtils;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.XMLEvent;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@SuppressWarnings("all")
@SpringBootTest
class ZiRuanXmlVTDGenTest {

   public static boolean isNumeric2(String str) {
      return str != null && str.matches("-?\\d+(\\.\\d+)?");
   }

   public static void main(String[] args) {


      boolean numeric2 = isNumeric2("23123123");
      boolean numeric3 = isNumeric2("-23-123123");
      System.out.println(numeric2);
      System.out.println(numeric3);

//      String ids = "123456";
//      String substring = ids.substring(0, 1);
//
//      System.out.println(substring);
//      test7();
//      test12();
   }

   /**
    * @email 1793327033@qq.com
    * @classname goslingApplicationTests2
    * @author: osc_lihonglin
    * @date: 2022/2/15 21:06
    */
   public static void test8() {
      try {
         VTDGen gen = new VTDGen();
         // 解析student.xml对象，不含有命名空间
         boolean parseFile = gen.parseFile("e:\\student.xml", false);
         if (parseFile) {
            VTDNav nav = gen.getNav();
            AutoPilot ap = new AutoPilot();
            AutoPilot ape = new AutoPilot();
            // 将导航器绑定到ap对像上
            // 如果把VTDNav表达为车辆上导航仪器的话，那么Autoap就代表开车人，他能更智能化的找到XPATH表达的含义
            ap.bind(nav);
            ape.bind(nav);
            // 设置重新设置一个xpath表达式的字符串，但是通常是在之后调用
            ape.selectXPath("/body/records/record");
            List<String> records = new ArrayList<>();
            String school = "";
            // evalXPath()返回nodeset集合中的下一个节点，如果检测到为匹配的节点，则返回为-1
            while (ape.evalXPath() != -1) {
               ap.selectXPath("school");
               school = ap.evalXPathToString();
               records.add(school);
            }
            ape.resetXPath();
            for (String s : records) {
               System.out.println("===" + s);
            }
         }
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }

   public static void test9() {
      try {
         //VTDGen是封装主要解析，索引加载和索引读取功能的类
         VTDGen vtdGen = new VTDGen();
         if (vtdGen.parseFile("D:\\123456.xml", true)) {
            //VTDNav是（1）封装XML，VTD和层次结构信息的类
            // （2）包含各种导航功能（3）执行各种比较以及VTD与字符串或数字数据转换功能的类
            VTDNav vtdNav = vtdGen.getNav();
            FileOutputStream fos = new FileOutputStream(new File("D:\\123456.xml"));
            //包含执行节点级迭代和XPath的函数。
            AutoPilot ap = new AutoPilot(vtdNav);
            //利用VTD-XML的增量更新功能的类
            XMLModifier xm = new XMLModifier(vtdNav);
            ap.selectXPath("/qwqwq/eleTest[@编码ID='12345']");
            int i = -1;
            while ((i = ap.evalXPath()) != -1) {
               xm.updateElementName("qqqqqqq");
//               xm.insertBeforeElement("<something/>\n");
//               xm.updateToken(i, "啊飒飒");
//               xm.remove();
            }
            ap.selectXPath("/qwqwq/eleTest[@编码ID='12345']");
            while ((i = ap.evalXPath()) != -1) {
               xm.insertBeforeElement("<something/>");
            }

            ap.selectXPath("/qwqwq/eleTest[@编码ID='12345']/text()");
            while ((i = ap.evalXPath()) != -1) {
               xm.updateToken(i, "asasasasasasa");
            }
            xm.output(fos);
            fos.close();
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static void test12() {
      String prefix = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "\n";
      String suffix = "\n</Employees>\n";
      try {

         VTDGenHuge vg = new VTDGenHuge();
         if (vg.parseFile("D:\\123456.xml", true, VTDGenHuge.MEM_MAPPED)) {
            int splitBy = prefix.length();
            VTDNavHuge vn = vg.getNav();
            AutoPilotHuge ap = new AutoPilotHuge(vn);
            ap.selectXPath("/qwqwq/eleTest");
            FastLongBuffer flb = new FastLongBuffer(4);
            int i;

            while ((i = ap.evalXPath()) != -1) {
               flb.append(vn.getElementFragment());
            }
            IByteBuffer vnXML = vn.getXML();
            byte[] xml = vn.getXML().getBytes();
            int size = flb.size();
            if (size != 0) {
               File fo = null;
               FileOutputStream fos = null;
               for (int k = 0; k < size; k++) {
                  if (k % splitBy == 0) {
                     if (fo != null) {
                        fos.write(suffix.getBytes());
                        fos.close();
                        fo = null;
                     }
                  }
                  if (fo == null) {
                     fo = new File("D:\\12345678.xml");
                     fos = new FileOutputStream(fo);
                     fos.write(prefix.getBytes());
                  }
                  fos.write("\n".getBytes());
                  fos.write(xml, flb.lower32At(k), flb.upper32At(k));
               }
               if (fo != null) {
                  fos.write(suffix.getBytes());
                  fos.close();
                  fo = null;
               }
            }

         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static void test13() {
      XMLInputFactory factory = XMLInputFactory.newInstance();
      InputStream is = null;
      try {
         is = new FileInputStream("D:\\123456.xml");
         XMLEventReader reader = factory.createXMLEventReader(is);
         while (reader.hasNext()) {
            XMLEvent event = reader.nextEvent();
            if (event.isStartElement()) {
               String name = event.asStartElement().getName().toString();
               if (name.equals("title")) {
                  System.out.print(reader.getElementText() + ":");
               } else if (name.equals("price")) {
                  System.out.print(reader.getElementText() + "\n");
               }
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         IOUtils.closeQuietly(is);
      }
   }

   public static void test7() {
      try {
         VTDGenHuge vtdGen = new VTDGenHuge();
         if (vtdGen.parseFile("D:\\123456.xml", false, VTDGenHuge.MEM_MAPPED)) {
            VTDNavHuge vtdNav = vtdGen.getNav();
            FileOutputStream fos = new FileOutputStream(new File("D:\\1234567.xml"));
            AutoPilotHuge ap = new AutoPilotHuge(vtdNav);
            XMLModifier xmlModifier = new XMLModifier();
            XMLMemMappedBuffer mlBuf = new XMLMemMappedBuffer();
            int i = -1;
            ap.selectXPath("//eleTest");
            while ((i = ap.evalXPath()) != -1) {
               int attrCount = vtdNav.getAttrCount();
               if (attrCount == 1) {
                  int text = vtdNav.getText();
                  System.out.println(vtdNav.toString(text));
                  vtdNav.push();
                  ap.resetXPath();
                  long tokenOffset = vtdNav.getTokenOffset(text) + vtdNav.getTokenLength(text);
                  long length = vtdNav.getXML().length();
//                  mlBuf.writeToFileOutputStream(fos, 0, 10);
//                  fos.write();
//                  xm.updateToken(text,"123");
               }
            }

            ap.selectXPath("//qqqqqqq");
            while ((i = ap.evalXPath()) != -1) {
               int attrCount = vtdNav.getAttrCount();

               if (attrCount == 1) {
                  int text = vtdNav.getText();
                  System.out.println(vtdNav.toString(text));
//                  xm.updateToken(text,"456");
               }
//               int attrVal1 = vtdNav.getAttrVal("编码数据ID");
//               String str1 = vtdNav.toString(attrVal1);
//               System.out.println("内容" + str1);
            }
//            xm.outputAndReparse();
//            for (Integer integer : list) {
//               xm.updateToken(integer,"cccccccccccccc");
//            }


//            ap.selectXPath("/电子文件封装包/被签名对象");
//            while ((i = ap.evalXPath()) != -1) {
//               xm.insertBeforeElement("<something>");
//               xm.insertAfterElement("</something>");
//               xm.outputAndReparse();
//            }
//
//            ap.selectXPath("/qwqwq/eleTest[@编码ID='12345']/text()");
//            while ((i = ap.evalXPath()) != -1) {
//               xm.updateToken(i, "asasasasasasa");
//            }

//            xm.output(fos);
            if (fos != null) {
               fos.close();
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static void test10() {
      try {
         VTDGen vg = new VTDGen();
         if (vg.parseFile("old.xml", false)) {
            VTDNav vn = vg.getNav();
            if (vn.toElement(VTDNav.FIRST_CHILD)) {
               int i = vn.getText();
               if (vn.overWrite(i, "123".getBytes()) == false) {
                  System.out.println("overWrite at " + i + " failed");
               }

               vn.toElement(VTDNav.NEXT_SIBLING);
               i = vn.getText();
               if (vn.overWrite(i, "234".getBytes()) == false) {
                  System.out.println("overWrite at " + i + " failed");
               }

               vn.toElement(VTDNav.NEXT_SIBLING);
               i = vn.getText();
               if (vn.overWrite(i, "new content".getBytes()) == false) {
                  System.out.println("overWrite at " + i + " failed");
               }

               byte[] ba = vn.getXML().getBytes();
               FileOutputStream fos = new FileOutputStream("new.xml");
               fos.write(ba);
            }
         }
      } catch (NavException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
      }
   }

   public synchronized void updateXmlPart(int j, VTDNav vn, String fileName, String changeContent) throws FileNotFoundException {
      //  File fo = new File("C:/work/workspaces/vtdtest/src/com/mytest/test5.xml");
      File fo = new File(fileName);
      FileOutputStream fos = new FileOutputStream(fo);
      // 进行定位修改
      if (j != -1) {
         // Get the starting offset of "1999-10-21"
         int os1 = vn.getTokenOffset(j);
         // Get the ending offset of "1999-10-21"
         int os2 = vn.getTokenOffset(j) + vn.getTokenLength(j);
         // Get the total number of bytes of XML
         int os3 = vn.getXML().length();

         byte[] xml = vn.getXML().getBytes();
         // Write everything before "1999-10-21"
         try {
            fos.write(xml, 0, os1);
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
         // Write "2006-6-17"
         try {
            fos.write(changeContent.getBytes());
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
         // Write everything after
         try {
            fos.write(xml, os2, os3 - os2);
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
         try {
            fos.close();
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
         // 修改完毕
      }
   }

   @Test
   void test3() {
      List<String> ids = new ArrayList<>();
      ids.add("12121");
      ids.add("134561");
      ids.add("8970");
      ids.add("4386");
      StringBuffer where = new StringBuffer();
      StringBuffer append = where.append(String.format("select * from table_from_1 and FIND_IN_SET(vol_id,'%s')", ids));
      System.out.println(append.toString());
   }

   @Test
   void date() {
      Calendar now = Calendar.getInstance();
      int year = now.get(Calendar.YEAR);
      int month = now.get(Calendar.MONTH) + 1;
      int day = now.get(Calendar.DAY_OF_MONTH);
      int hour = now.get(Calendar.HOUR_OF_DAY);
      int minute = now.get(Calendar.MINUTE);
      int second = now.get(Calendar.SECOND);
      long timeInMillis = now.getTimeInMillis();
      System.out.println("年: " + year);
      System.out.println("月: " + month);
      System.out.println("日: " + day);
      System.out.println("时: " + hour);
      System.out.println("分: " + minute);
      System.out.println("秒: " + second);
      System.out.println("当前时间毫秒数：" + timeInMillis);
      System.out.println(now.getTime());
      Date d = new Date();
      System.out.println(d);
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 'T' HH:mm:ss");
      String dateNowStr = sdf.format(d);
      System.out.println("格式化后的日期：" + dateNowStr);
   }

   @Test
   void contextLoads() {
      //盐
      String salt = "JHMaZDuGAP";
      //密码
      String password = "admin";
      //盐+密码进行MD5加密的字节数组
      String md5 = DigestUtils.md5DigestAsHex((password + salt).getBytes());
      //总共 1或者2月份——现在 ：633
      int countAll = 110 + 103 + 200 + 110 + 90 + 20;
      //一共多少户
      BigDecimal household = new BigDecimal(6);
      //原来方式计算：总价钱/总人数
      BigDecimal bigDecimal = new BigDecimal(countAll);
      //每个人应该缴纳 105.5
      BigDecimal divide = bigDecimal.divide(household);
      //上述计算错误

      //------------------------------------ 水费计算 按均分配-----------------------------------
      // 水费总数 / 总天数 = 所有的租户每天应该给多少钱（应该是1-8月份）
      // 所有的租户每天应该给多少钱 / 所有的租户（包含搬走的）= 每个人每天应该给多少
      // 每个人每天应该给多少钱 * 当前租户在这里租了多久的天数 = 当前租户在租房期间一共要给多少钱（包含搬走的）
      //---------------------------------------------------------------------------------------

      List<String> ids = new ArrayList<>();
      ids.add("12121");
      ids.add("134561");
      ids.add("8970");
      ids.add("4386");
      StringBuffer where = new StringBuffer();
//        StringBuffer append = where.append(" and vol_id in (" + ids + ")");
      StringBuffer append = where.append(String.format("  vol_id in ('%s')", ids));
      System.out.println(append.toString());
      where.append(String.format(" and FIND_IN_SET(vol_id,'%s')", ids));

   }

}
